---
title: "Decomposition Results"
output: html_notebook
---

```{r setup}
library(tidyverse)
```


## Table 5: Decomposition results

```{r}
# load data
df <- 
  read_csv('../pyfiles/decompose_main.csv') %>% 
  select(-...1) %>% 
  filter(type2to3 %in% c("A", "B") ) %>%
  mutate(id = row_number()) %>% 
  select(id, everything())
df
```


```{r}
# aggregate
df_mean <- 
  df %>% 
  filter(type2to3 %in% c("A", "B") ) %>%
  group_by(type2to3) %>%
  summarize(across(.cols = c("total_2half", "price_2half", 
                             "substitution_2half", "income_2half"), 
                   .fns = list(mean = mean)   )) %>%
  rename(total = total_2half_mean,
         price = price_2half_mean,
         subs = substitution_2half_mean,
         income = income_2half_mean) 

# Table 5, first two rows
df_mean 

# Table 5, last two rows
df_mean %>%
  pivot_wider(names_from = type2to3, values_from = c('total', 'price', 'subs', 'income') ) %>%
  mutate(total_dif = total_B - total_A,
         price_dif = price_B - price_A,
         subs_dif = subs_B - subs_A,
         income_dif = income_B - income_A) %>%
  mutate(price_ratio = price_dif / total_dif, 
         subs_ratio = subs_dif / total_dif,
         income_ratio = income_dif / total_dif) %>%
  select(ends_with("_dif"), ends_with("_ratio"))

# price: 3.5%
# substitution: 17.4%
# income: 79.1%
```

## Figure 4: Decompsoition results for a representative type-B mother

```{r}
df_decomp_B <- 
  read_csv('../pyfiles/decompose_averageB.csv') %>%
  select(n, q, total, price, substitution, income)

df_decomp_B %>%
  ggplot(aes(x = n)) +
  geom_line(aes(y = total), linetype = "solid") +
  geom_point(aes(y= price), shape = 6) +
  geom_point(aes(y= substitution), shape = 0) +
  geom_line(aes(y = income), linetype = "dashed") +
  labs(x = "Fertility", 
       y = "",
       title = "Decomposition of the QQ effect") +
  geom_hline(yintercept = 0, linetype = "dotted") + 
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5, size = 16)) +
  annotate("text", x = 1.5, y = 1.5, label = "QQ effect") +
  annotate("text", x = 1.3, y = -0.3, label = "Price effect") +
  annotate("text", x = 1.3, y = 0.3, label = "Substitution effect") +
  annotate("text", x = 2, y = 1.2, label = "Rationing income effect") +
  geom_segment(aes(x = 1.1, y = 1.4, xend = 1.25, yend = 1.45), arrow = arrow(length = unit(0.3, "cm"))) + 
  geom_segment(aes(x = 1.25, y = 0.95, xend = 1.6, yend = 1.12), arrow = arrow(length = unit(0.3, "cm")))

ggsave("Figure4_decomp_B.pdf", path = "../output",
       width = 8, height = 5)
```










